import {CloseOutlined, PlusOutlined} from '@ant-design/icons';
import {Button, Input, message, Popconfirm, Select} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';

import CreateForm from './components/CreateForm';

import {queryRule, queryStore, queryGiveaway, addActivity, updateActivity} from './service';
import EditTableStore from "@/pages/PositionManagement/components/EditTableStore";
import styles from "@/global.less";

const TableList = (props) => {
  const activityType = 2;
  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpModalVisible] = useState(false);
  const actionRef = useRef();
  const formRef = useRef();
  const [formValue, setFormValue] = useState({});
  const [storeArr, setStoreArr] = useState([]);
  const [children, setChildren] = useState([]);
  const [Selected, setSelected] = useState([]);
  const [storeValue, setStoreValue] = useState([]);
  const [selectedArray, setSelectedArray] = useState([]);
  const handleGetStore = async () => {
    const {data} = await queryStore();
    setStoreArr(data);
  };
  const StoreSelect = (record, selected, selectedRows) => {
    if (selected) {
      const list = [record.id];
      setChildren(list.concat(children));
      const selectList = [record];
      setSelected(Selected.concat(selectList));
    } else {
      setChildren(children.filter(id => id !== record.id));
      setSelected(Selected.filter(rec => rec.id !== record.id));
    }
  };
  const StoreSelectChange = (selectedRowKeys, selectedRows, info) => {

  };
  const StoreSelectAll = (selected, selectedRows, changeRows) => {
    if (selected) {
      setChildren(selectedRows.map(record => record.id))
    } else {
      setChildren([])
    }
    setSelected(selectedRows);
  };
  const handleCommissionChild = (value) => {
    const list = JSON.parse(JSON.stringify(storeValue));
    list.map((item) => {
      if (item.storeId === value.id) {
        if (value.id === item.storeId) {
          item.commission = value.commission;
        }
      }
    });
    Selected.map((item) => {
      item.id === value.id
        ? ((item.commission = value.commission), (item.positionId = positionId))
        : null;
    });
    setStoreValue(list);
  };
  const searchStateFun = () => {
    setSelectedArray(Selected);
  };
  useEffect(() => {
    handleGetStore();
  }, []);
  const createConsumeActivity = (value) => {
    value.stores = Selected.map(store => {
      return store.id
    });
    value.type = activityType;
    addActivity(value).then(res => {
      if (res.code === 0) {
        message.info("创建成功")
        actionRef.current.reload();
      }
      handleModalVisible(false);
    })
  };
  const updateConsumeActivity = (value) => {
    value.stores = Selected.map(store => {
      return store.id
    });
    value.type = activityType;
    value.id = formValue.id;
    updateActivity(value).then(res => {
      if (res.code === 0) {
        message.info("更新成功")
        actionRef.current.reload();
      }
      handleUpModalVisible(false);
    })
  };
  const columns = [
    {
      title: '活动名',
      dataIndex: 'activityName',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
      render: (dom, entity) => {
        return <a>{dom}</a>;
      },
    },
    {
      title: '活动类型',
      dataIndex: 'subType',
      initialValue: 1,
      valueEnum: {
        1: {
          text: '满减',
          status: 'Processing',
        },
        3: {
          text: '满赠',
          status: 'Success',
        },
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '活动类型为必填项',
          },
        ],
      },
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select defaultValue={defaultRender.priceType} placeholder="请选择活动类型" allowClear>
            <Select.Option value={1}>满减</Select.Option>
            <Select.Option value={3}>满赠</Select.Option>
          </Select>
        );
      },
    },
    {
      title: '活动范围',
      dataIndex: 'allStore',
      hideInSearch: true,
      hideInForm: true,
      valueEnum: {
        true: {
          text: '全场通用',
          status: 'Processing',
        },
        false: {
          text: '部分店铺',
          status: 'Success',
        },
      },
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      hideInSearch: true,
      valueType: 'dateTime',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '开始时间为必填项',
          },
        ],
      },
      render: (_, record) => {
        if (record.createTime) {
          return new Date(record.startTime).toLocaleString();
        } else {
          return '-';
        }
      },
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      hideInSearch: true,
      valueType: 'dateTime',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '结束时间为必填项',
          },
        ],
      },
      render: (_, record) => {
        if (record.createTime) {
          return new Date(record.endTime).toLocaleString();
        } else {
          return '-';
        }
      },
    },
    {
      title: '满(多少)',
      dataIndex: 'activityFull',
      valueType: 'money',
      hideInSearch: true,
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '满(多少)为必填项',
          },
        ],
      },
    },
    {
      title: '减(多少)',
      dataIndex: 'activityReduc',
      valueType: 'money',
      hideInSearch: true,
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '减(多少)为必填项',
          },
        ],
      },
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        const subType = form.getFieldValue("subType");
        return subType === 1 ? (
          defaultRender(item)
        ) : null;
      },
    },
    {
      title: '赠(多少)',
      dataIndex: 'activityReduc',
      valueType: 'money',
      hideInSearch: true,
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '赠(多少)为必填项',
          },
        ],
      },
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        const subType = form.getFieldValue("subType");
        return subType === 3 ? (
          defaultRender(item)
        ) : null;
      },
    },
    {
      title: '参加店铺',
      dataIndex: 'storeList',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <EditTableStore
            dataSource={storeArr}
            onSelect={StoreSelect}
            onSelectAll={StoreSelectAll}
            onChange={StoreSelectChange}
            handleChildren={children}
            childrenCommission={handleCommissionChild}
            searchState={searchStateFun}
            CommissionState={false}
          />
        );
      },
    },
    {
      title: '已选店铺(默认全场通用)',
      dataIndex: 'selected',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <div className="selected_div">
            {Selected.map((item, index) => {
              return (
                <div key={index} className="store_selected">
                  <span>{item.name}</span>
                  <Popconfirm
                    title="确定删除该店铺吗?"
                    onConfirm={() => {
                      const handleId = JSON.parse(JSON.stringify(children));
                      const list = JSON.parse(JSON.stringify(Selected));
                      list.map((item_, index) => {
                        if (item.id === item_.id) {
                          return list.splice(index, 1);
                        }
                      });
                      handleId.map((item_, index) => {
                        if (item.id === item_) {
                          return handleId.splice(index, 1);
                        }
                      });
                      setSelected(list);
                      setChildren(handleId);
                    }}
                    okText="是"
                    cancelText="否"
                  >
                    <CloseOutlined style={{color: 'red', cursor: 'pointer'}}/>
                  </Popconfirm>
                </div>
              );
            })}
          </div>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <a
          onClick={() => {
            console.log(record)
            setFormValue(record);
            setChildren(record.stores);
            if (!record.stores) {
              record.stores = [];
            }
            const selectStores = storeArr.filter(store => {
              return record.stores.includes(store.id)
            });
            setSelected(selectStores);
            handleUpModalVisible(true);
          }}
        >
          修改
        </a>
      ),
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="充值活动列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        scroll={{x: 1200}}
        bordered
        toolBarRender={() => [
          <Button type="primary" onClick={() => {
            setSelected([]);
            setChildren([]);
            handleModalVisible(true);
          }}>
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={(params, sorter, filter) => queryRule({...params, sorter, filter, type: activityType})}
        postData={(payload) => {
          const {list, total} = payload;
          return list || [];
        }}
        columns={columns}
      />
      <CreateForm onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible} btn_view={null}
                  width={1200}>
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            createConsumeActivity(value);
          }}
          rowKey="id"
          bordered
          type="form"
          formRef={formRef}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
          }}
          columns={columns}
        />
      </CreateForm>

      <CreateForm onCancel={() => handleUpModalVisible(false)} modalVisible={updateModalVisible} btn_view={null}
                  width={1200}>
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            updateConsumeActivity(value);
          }}
          rowKey="id"
          bordered
          type="form"
          formRef={formRef}
          form={{
            initialValues: formValue,
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
          }}
          columns={columns}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
